import React, { useEffect, useState, useRef } from 'react';
import { Result, Button, Select, Form, message, Input, Modal } from 'antd';
import { connect } from 'dva';
import PubSub from 'pubsub-js';
import SlickTable from '@/components/SlickTable';
import ScrollBar from '@/components/ScrollBar';
import RuleComponent from './components/RuleComponent';
import styles from './index.less';
import request from '@/utils/request';
// import SetCondition from './components/SetCondition';

const { Option } = Select;
const eventName = 'ruleConfig_planTable';

function Content(props) {
  const userEl = useRef(null);
  const { getFieldDecorator } = props.form;
  // 状态 方案type:plan , 规则 type:rule
  const [status, setStatus] = useState('');
  // rule 与 plan 的接口数据
  const [data, setData] = useState([]);
  // // 请求状态
  const [loading, setLoading] = useState(false);
  // 保存记录type：rule 的模式 精简模式：simplify  操作模式：operate

  const [editingKey, setEditingKey] = useState('');

  const queryPlan = curId => {
    setLoading(true);
    request('pmc/pms/RuleCfgController/findRulesByPlan', {
      data: {
        planId: curId,
      },
    })
      .then(res => {
        if (res.success) {
          setData(res.data);
          setEditingKey('');
        } else {
          message.error(res.errMessage);
        }
      })
      .always(() => {
        setLoading(false);
      });
  };

  useEffect(() => {
    if (!props.id) return;
    /**
     * props.id的格式为 " type,id "
     * 当前选中项的type:CurStatus及选中项Id：Curid
     */
    const curStatus = props.id.match(/_(\S*)/)[1];
    const curId = props.id.match(/(\S*)_/)[1];
    if (curStatus === 'plan') {
      queryPlan(curId);
    }
    setStatus(curStatus);
  }, [props.id]);

  // 新增监听 刷新方案新增规则下提交完 规则管理表格数据的更新
  useEffect(() => {
    // 监听订阅
    PubSub.subscribe(`${eventName}.update`, () => {
      queryPlan(props.id.match(/(\S*)_/)[1]);
    });
    return () => {
      PubSub.unsubscribe(`${eventName}`);
    };
  });

  /**
   * 此模块为type:plan的逻辑模块
   * 涉及:归属环节、业务类型
   * 模块
   */

  const isEditing = record => {
    return record.ruleId === editingKey;
  };

  const saveTable = record => {
    request('pmc/pms/RuleCfgController/editRuleRel', {
      data: {
        planId: record.pid,
        ruleRelId: record.ruleRelId,
        ruleId: record.ruleId,
        priority: props.form.getFieldValue('priority'),
        relType: props.form.getFieldValue('relType'),
        relyonRuleId: props.form.getFieldValue('relyonRuleId'),
        autoExe: record.autoExe,
      },
    }).then(res => {
      if (res.success) {
        message.success('修改规则成功！');
        queryPlan(props.id.match(/(\S*)_/)[1]);
      } else {
        message.error(res.errMessage);
      }
    });
  };

  const columns = [
    {
      title: '规则编码',
      dataIndex: 'ruleId',
      ellipsis: true,
    },

    {
      title: '规则名称',
      dataIndex: 'ruleName',
      ellipsis: true,
    },
    {
      title: '优先级',
      dataIndex: 'priority',
      ellipsis: true,
      render: (text, record) => {
        /* eslint-disable */
        const editable = isEditing(record);
        return editable ? (
          <Form.Item style={{ marginBottom: 0 }}>
            {getFieldDecorator('priority', {
              initialValue: record.priority,
            })(<Input placeholder="请输入" />)}
          </Form.Item>
        ) : (
          text
        );
      },
    },
    {
      title: '规则关系',
      dataIndex: 'relType',
      width: 140,
      ellipsis: true,
      render: (text, record) => {
        /* eslint-disable */
        const editable = isEditing(record);
        return editable ? (
          <Form.Item style={{ marginBottom: 0 }}>
            {getFieldDecorator('relType', {
              initialValue: record.relType,
            })(
              <Select placeholder="请选择组织" style={{ width: 120 }}>
                <Option value="0">并行</Option>
                <Option value="1">依赖</Option>
                <Option value="2">互斥</Option>
                <Option value="3">全部互斥</Option>
              </Select>
            )}
          </Form.Item>
        ) : text === '0' ? (
          `并行`
        ) : text === '1' ? (
          '依赖'
        ) : text === '2' ? (
          '互斥'
        ) : (
          '全部互斥'
        );
        /* eslint-enable */
      },
    },
    {
      title: '关系值',
      dataIndex: 'relyonRuleId',
      ellipsis: true,
      render: (text, record) => {
        /* eslint-disable */
        const editable = isEditing(record);
        return editable ? (
          <Form.Item style={{ marginBottom: 0 }}>
            {getFieldDecorator('relyonRuleId', {
              initialValue: record.relyonRuleId,
            })(<Input placeholder="请输入" />)}
          </Form.Item>
        ) : (
          text
        );
      },
    },
    {
      title: '操作',
      width: 100,
      align: 'center',
      render: (text, record) => {
        const editable = isEditing(record);
        return editable ? (
          <>
            <a
              onClick={() => {
                if (
                  props.form.getFieldValue('relType') === '1' ||
                  props.form.getFieldValue('relType') === '2'
                ) {
                  if (!props.form.getFieldValue('relyonRuleId')) {
                    Modal.warning({
                      content: '关系值不能为空，请填写对应关系值！',
                    });
                  } else {
                    saveTable(record);
                    PubSub.publish(`ruleConfig_tree.update`);
                  }
                } else if (
                  props.form.getFieldValue('relType') === '0' ||
                  props.form.getFieldValue('relType') === '3'
                ) {
                  if (props.form.getFieldValue('relyonRuleId')) {
                    Modal.confirm({
                      content: '关系值需为空值，是否确定关系值置空',
                      onOk() {
                        props.form.setFieldsValue({
                          relyonRuleId: '',
                        });
                        saveTable(record);
                        PubSub.publish(`ruleConfig_tree.update`);
                      },
                    });
                  } else {
                    saveTable(record);
                    PubSub.publish(`ruleConfig_tree.update`);
                  }
                }
              }}
              style={{ marginRight: 8 }}
            >
              保存
            </a>

            <a
              onClick={() => {
                setEditingKey('');
              }}
            >
              取消
            </a>
          </>
        ) : (
          <a
            disabled={editingKey !== ''}
            onClick={() => {
              setEditingKey(record.ruleId);
            }}
          >
            编辑
          </a>
        );
      },
    },
  ];

  // type：plan 方案的模板渲染
  const renderPlan = (
    <>
      <div className="ant-detail-title">规则管理</div>
      <SlickTable
        rowKey={record => record.ruleId}
        columns={columns}
        pagination={false}
        dataSource={data}
        loading={loading}
      />
    </>
  );

  // type：rule 的模板渲染
  const renderRule = (
    <RuleComponent
      operType="detail"
      ruleId={
        props.id
          ? props.id.match(/_(\S*)/)[1] === 'rule'
            ? props.id.match(/(\S*)_/)[1]
            : 'none_status'
          : 'none_status'
      }
      ref={userEl}
      cRef={userEl}
    />
  );

  return (
    <div className={styles.right_scroll_content}>
      <ScrollBar autoHide autoHeight autoHeightMax={props.height - 110}>
        <div className={styles.right_content} style={{ height: props.height - 110 }}>
          {status === 'plan' ? renderPlan : null}
          {status === 'rule' ? renderRule : null}
          {status !== 'rule' && status !== 'plan' ? (
            <div className={styles.vertical_center}>
              <Result status="404" subTitle="目录无配置区，请选择正确层级进行规则配置" />
            </div>
          ) : null}
        </div>
      </ScrollBar>
      {status === 'rule' ? (
        <div
          style={{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
          }}
        >
          <Button
            type="primary"
            onClick={() => {
              userEl.current.handleAdd().then(res => {
                if (res === true) {
                  PubSub.publish(`ruleConfig_tree.update`);
                }
              });
            }}
          >
            保存
          </Button>
        </div>
      ) : null}
    </div>
  );
}

export default connect(({ ruleConfig2 }) => ({
  id: ruleConfig2.id,
}))(Form.create()(Content));
